//
//  SQLiteTool.m
//
//  Created by 周成龙
//

#import "SQLiteTool.h"
#import <sqlite3.h>


static NSString *const dbName = @"sk_db.sqlite";
NSString *const kTableName = @"sk_table_name";

@implementation SQLiteTool
static SQLiteTool *_tool = nil;
sqlite3 *_sqdb;

+ (instancetype)shareSQLiteTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _tool = [[SQLiteTool alloc] init];
    });
    return _tool;
}

- (BOOL)openDB {
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    filePath = [filePath stringByAppendingPathComponent:dbName];
    
    if (sqlite3_open(filePath.UTF8String, &_sqdb) != SQLITE_OK) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    return [self createTable];
}

- (BOOL)createTable {
    NSString *creatTableSql = [NSString stringWithFormat:@"create table if not exists '%@' ('sid' text not NULL primary key, 'uid' text, 'unique' text, 'content' text, 'img_url' blob, 'create_time' text, 'update_time' text, 'alert_time' text, 'status' text);", kTableName];
    return [self execSql:creatTableSql];
}

- (BOOL)execSql:(NSString *)sql {
    return (sqlite3_exec(_sqdb, sql.UTF8String, nil, nil, nil) == SQLITE_OK) ? YES : NO;
}

- (void)closeDB {
    sqlite3_close(_sqdb);
}

/// 查询所有查
- (NSArray *)qureySqlite:(NSString *)querySql {
    sqlite3_stmt*stmt = nil;
    
    if (sqlite3_prepare_v2(_sqdb, querySql.UTF8String, -1, &stmt, nil) != SQLITE_OK) {
        NSLog(@"数据查询失败");
        return nil;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int count = sqlite3_column_count(stmt);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        for (int i = 0; i < count; i ++) {
            const char *cKey = sqlite3_column_name(stmt, i);
            NSString *key = [NSString stringWithUTF8String:cKey];
            
            const char *cValue = (const char *)sqlite3_column_text(stmt, i);
            NSString *value = [NSString stringWithUTF8String:cValue];
            [dict setValue:value forKey:key];
        }
        [array addObject:dict];
        sqlite3_finalize(stmt);
    }
    return array;
}

@end
